<?php

namespace App\Admin\Controllers;

use App\Models\Order;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;

class OrderController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Order(), function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->column('id')->sortable();
            $grid->column('order_number');
            $grid->column('name');
            $grid->column('phone');
            // $grid->column('email');
            $grid->column('postal_code');
            $grid->column('country');
            $grid->column('province');
            $grid->column('city');
            $grid->column('address');
            $grid->column('remark');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                //自动展开
                $filter->expand();
                $filter->equal('id')->width(2);
                $filter->like('order_number')->width(2);
                $filter->like('name')->width(2);
                $filter->like('phone')->width(2);
                // $filter->like('email')->width(2);
                $filter->like('postal_code')->width(2);
                $filter->like('country')->width(2);
                $filter->like('province')->width(2);
                $filter->like('city')->width(2);
                $filter->like('address')->width(2);
                //时间搜索
                $filter->between('created_at')->datetime()->width(4);
            });
            $grid->export()->csv();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        Admin::style(
            <<<CSS
            @media print {
                .main-footer,.box-header
                {
                    display: none !important;
                }
            }
            CSS
        );
        Admin::script(
            <<<JS
        function _printWithOrientation(orientation) {
            var styleId = 'print-orientation-style';
            var existing = document.getElementById(styleId);
            if (existing) existing.parentNode.removeChild(existing);

            var style = document.createElement('style');
            style.id = styleId;
            // portrait 或 landscape
            style.innerHTML = '@page { size: A4 ' + (orientation === 'landscape' ? 'landscape' : 'portrait') + '; }';
            document.head.appendChild(style);

            // 适当延时以确保样式生效
            setTimeout(function () {
                window.print();
                setTimeout(function () {
                    var s = document.getElementById(styleId);
                    if (s) s.parentNode.removeChild(s);
                }, 500);
            }, 100);
        }
        window.printPortrait = function() { _printWithOrientation('portrait'); };
        window.printLandscape = function() { _printWithOrientation('landscape'); };
        JS
        );
        return Show::make($id, new Order(), function (Show $show) use ($id) {
            $show->row(function (Show\Row $show) {
                $show->width(6)->name;
                $show->width(6)->phone;
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->postal_code;
                $show->width(6)->country;
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->province;
                $show->width(6)->city;
            });
            $show->row(function (Show\Row $show) {
                $show->width(12)->address;
            });
            $show->row(function (Show\Row $show) {
                $show->width(12)->remark;
            });
            $show->row(function (Show\Row $show) use ($id) {
                $show->html(function () use ($id) {
                    static $rendered = false;
                    if ($rendered) {
                        return '';
                    }
                    $rendered = true;
                    $order = Order::find($id);
                    $orderNumber = $order ? $order->order_number : '';
                    $generator     = new \Picqer\Barcode\BarcodeGeneratorPNG();
                    $barcodeData   = $generator->getBarcode($orderNumber ?: ' ', $generator::TYPE_CODE_128);
                    $base64Barcode = base64_encode($barcodeData);

                    return '<div style="text-align: center; margin: 20px 0;">
                        <img src="data:image/png;base64,' . $base64Barcode . '"
                             alt="订单条形码" style="height: 60px;">
                        <p style="margin-top: 10px;">' . htmlentities($orderNumber, ENT_QUOTES, 'UTF-8') . '</p>
                     </div>';
                });
            });
            // 添加订单条形码显示

            $show->tools(function (Show\Tools $tools) {
                $tools->append('<button onclick="printPortrait()" class="btn btn-sm btn-primary">
                                <i class="feather icon-printer"></i> 纵向打印
                            </button>&nbsp;');
                $tools->append('<button onclick="printLandscape()" class="btn btn-sm btn-primary">
                                <i class="feather icon-printer"></i> 横向打印
                            </button>&nbsp;');
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Order(), function (Form $form) {
            $form->display('id');
            if ($form->isCreating()) {
                $form->hidden('order_number')->value($this->makeOrderSn());
            } else {
                //修改的时候订单可以修改但是不能和其他订单号重复
                $form->text('order_number')->rules('unique:orders,order_number,' . $form->model()->id, [
                    'unique' => '订单号已存在，请重新输入',
                ]);
            }

            $form->text('name')->required();
            $form->text('phone')->required();
            $form->text('country')->required();
            $form->text('province')->required();
            $form->text('city')->required();
            // $form->text('email')->required();
            $form->text('postal_code')->required();
            $form->text('address')->required();
            $form->textarea('remark')->saving(function ($value) {
                return $value ?: '';
            });
            $form->display('created_at');
            $form->display('updated_at');
        });
    }

    //自动生成一个不重复的订单号
    protected function makeOrderSn()
    {
        $orderSn = 'ORD' . date('YmdHis') . rand(1000, 9999);
        $order   = Order::where('order_number', $orderSn)->first();
        if ($order) {
            $this->makeOrderSn();
        }
        return $orderSn;
    }
}
